package com.cloud.school.app.config.security;

import com.cloud.school.app.config.CacheService;
import com.cloud.school.app.util.exception.SystemHandleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ValidateCode {

    public static volatile Environment env = null;

    private static final int timeInSecond = 300;
    private static final Random r = new Random();
    private static final String TELE_VALIDATE_CODE = "telephoneValidateCode.";

    public static boolean validateCode(String validateCode, String telephone, CacheService cacheService) {
        if (StringUtils.isEmpty(validateCode)) {
            return false;
        }
        String redisValidateCode = getTeleValidateCode(cacheService, telephone);
        if (!validateCode.equalsIgnoreCase(redisValidateCode)) {
            return false;
        }
        return true;
    }

    public static String getTeleValidateCode(CacheService cacheService, String telephone) {
        if (env.acceptsProfiles(Profiles.of("dev"))) {
            return "123456";
        }
        return cacheService.get(TELE_VALIDATE_CODE + telephone);
    }

    public static boolean removeTeleValidateCode(CacheService cacheService, String telephone) {
        return cacheService.delete(TELE_VALIDATE_CODE + telephone);
    }

    /**
     * 生成验证码
     * 00 提交成功
     * 1 参数不完整，请检查所带的参数名是否都正确
     * 2 鉴权失败，一般是用户名密码不对
     * 3 号码数量超出50 条
     * 4 发送失败
     * 5 余额不足
     * 6 发送内容含屏蔽词
     * 7 短信内容超出350个字
     * 72 内容被审核员屏蔽
     * 8:OverLimit! 号码列表中没有合法的手机号码或手机号为黑名单或验证码类每小时超过限制条数
     * 9 夜间管理，不允许一次提交超过20个号码 8
     */
    public static void sendMessage(CacheService cacheService, String telephone) {
        if (env.acceptsProfiles(Profiles.of("dev"))) {
            return;//dev环境直接返回
        }
        String validateCode = getRandNum(6);// 验证码生成
        if (cacheService.putIfAbsent(TELE_VALIDATE_CODE + telephone, validateCode, timeInSecond, TimeUnit.SECONDS)) {
            // 发送短信
//            AliyunSendSms.sendSms(telephone, validateCode);
            DefaultSendSms.sendSms(telephone, validateCode);
        } else {
            throw new SystemHandleException("验证码已发送，请勿频繁请求验证码！");
        }
    }

    private static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }

    private static int randomInt(int from, int to) {
        return from + r.nextInt(to - from);
    }

    public static void setEnv(Environment env) {
        ValidateCode.env = env;
    }
}
